﻿using CnBlogsCore.Interface;
using CnBlogsCore.Model;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace CnBlogsCore.Services
{
    public class NewsService : INewsService
    {
        public string GetNewsDetail(string token, string tokenType, int id)
        {
            var client = new RestClient(Global.CnBlogsUrl.RecentNewsUrl);
            client.Authenticator =
                new RestSharp.Authenticators.OAuth2AuthorizationRequestHeaderAuthenticator(
                    token,
                    tokenType);

            var request = new RestRequest(Global.CnBlogsUrl.NewsDetailArgs).AddUrlSegment("id", id);

            var response = client.Execute(request, Method.GET);

            string resultBody = "";

            if (response.StatusCode == HttpStatusCode.OK)
            {
                resultBody = JsonConvert.DeserializeObject<string>(response.Content.ToString());
            }

            return resultBody;
        }

        public List<News> GetRecentNews(string token, string tokenType, int pageIndex, int pageSize)
        {
            return GetNews(Global.CnBlogsUrl.RecentNewsUrl, token, tokenType, pageIndex, pageSize);
        }

        public List<News> GetRecommendedNews(string token, string tokenType, int pageIndex, int pageSize)
        {
            return GetNews(Global.CnBlogsUrl.RecommendedNewsUrl, token, tokenType, pageIndex, pageSize);
        }

        public List<News> GetWeekHotNews(string token, string tokenType, int pageIndex, int pageSize)
        {
            return GetNews(Global.CnBlogsUrl.WeekHotNewsUrl, token, tokenType, pageIndex, pageSize);
        }

        private List<News> GetNews(string url, string token, string tokenType, int pageIndex, int pageSize)
        {
            var client = new RestClient(url);
            client.Authenticator =
                new RestSharp.Authenticators.OAuth2AuthorizationRequestHeaderAuthenticator(
                    token,
                    tokenType);

            RestRequest request = new RestRequest();
            request.AddParameter("pageIndex", pageIndex);
            request.AddParameter("pageSize", pageSize);

            var response = client.Execute(request, Method.GET);

            List<News> news = null;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string result = response.Content;
                news = JsonConvert.DeserializeObject<List<News>>(result);
            }

            return news;
        }
    }
}
